package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Transactional
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        // 1. 判断本菜品是否以存在
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 判断当前添加的是菜品还是套餐
        if (shoppingCart.getDishId() != null) {
            lambdaQueryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        } else {
            lambdaQueryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }

        ShoppingCart cart = this.getOne(lambdaQueryWrapper);

        if (cart != null) {
            // 2. 存在，数量加一
            cart.setNumber(cart.getNumber() + 1);
            this.updateById(cart);
        } else {
            // 3. 不存在，添加数据到购物车，数量为一
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());

            this.save(shoppingCart);
            cart = shoppingCart;
        }

        return cart;
    }

    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        // 1. 更具商品id 查询出具体的购物车对应的数据
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId());
        lambdaQueryWrapper.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        ShoppingCart cart = this.getOne(lambdaQueryWrapper);

        // 判断数据是否为空
        if (cart != null) {

            // 2. 数量减一
            cart.setNumber(cart.getNumber() - 1);

            // 3. 判断商品数量
            if (cart.getNumber().equals(0)) {

                // 删除数据库中的数据
                this.removeById(cart);

            } else {

                // 更新数据库
                this.updateById(cart);

            }
        }
        return cart;
    }
}
